# main.py
from PyQt6 import QtWidgets
from PyQt6.QtCore import pyqtSlot , Qt
from PyQt6.QtGui import QFont
import sys
import os
import json
from .Ui_information_lists import Ui_Dialog  # 这是 pyuic6 自动生成的类
from pathlib import Path
import logging
class InformationLists(QtWidgets.QDialog, Ui_Dialog):
    def __init__(self):
        super().__init__()
        self.ui = Ui_Dialog()
        self.ui.setupUi(self)

        # UI 初始化后，设置逻辑
        self.init_ui_logic()
        self.load_json_to_table("message_data.json")  # 程序启动时读取
    def init_ui_logic(self):
        # 禁止表格编辑
        self.ui.tableWidget.setEditTriggers(QtWidgets.QAbstractItemView.EditTrigger.NoEditTriggers)
    def load_json_to_table(self, filename):
        logger = logging.getLogger(__name__)
        logger.info(f"开始加载 JSON 文件: {filename}")

        try:
            # json_path = Path(__file__).resolve().parent.parent / filename
            json_path = Path(__file__).resolve().parent.parent /+'_internal/'+ filename
            logger.info(f"JSON 文件路径: {json_path}")
            logger.info(f"当前目录：{os.getcwd()}")
            if not json_path.exists():
                logger.error(f"未找到文件: {json_path}")
                return
        except Exception as e:
            logger.exception(f"获取 JSON 文件路径时发生异常: {e}")
            return

        try:
            with open(json_path, 'r', encoding='utf-8') as f:
                data_list = json.load(f)
            logger.info(f"成功读取 JSON 文件，记录条数: {len(data_list)}")
        except Exception as e:
            logger.exception(f"读取或解析 JSON 文件时出错: {e}")
            return

        try:
            self.ui.tableWidget.setRowCount(len(data_list))
        except Exception as e:
            logger.exception(f"设置表格行数时出错: {e}")
            return

        for row_index, item in enumerate(data_list):
            try:
                self.ui.tableWidget.setItem(row_index, 0, QtWidgets.QTableWidgetItem(item["name"]))
            except Exception as e:
                logger.warning(f"第 {row_index} 行设置“name”列出错: {e}")

            try:
                self.ui.tableWidget.setItem(row_index, 2, QtWidgets.QTableWidgetItem(item["color"]))
            except Exception as e:
                logger.warning(f"第 {row_index} 行设置“color”列出错: {e}")

            try:
                self.ui.tableWidget.setItem(row_index, 3, QtWidgets.QTableWidgetItem(item["data"]))
            except Exception as e:
                logger.warning(f"第 {row_index} 行设置“data”列出错: {e}")

            try:
                type_val = item.get("type", "")
                if type_val == "pass":
                    self.ui.tableWidget.setItem(row_index, 4, QtWidgets.QTableWidgetItem("否"))
                else:
                    self.ui.tableWidget.setItem(row_index, 4, QtWidgets.QTableWidgetItem("是"))
            except Exception as e:
                logger.warning(f"第 {row_index} 行设置“type”列出错: {e}")

            try:
                self.ui.tableWidget.setVerticalHeaderItem(row_index, QtWidgets.QTableWidgetItem(str(item.get("num", ""))))
            except Exception as e:
                logger.warning(f"第 {row_index} 行设置行头“num”出错: {e}")

        logger.info("JSON 数据加载到表格完成")
# 启动程序
def main():
    os.environ["QT_AUTO_SCREEN_SCALE_FACTOR"] = "1"

    app = QtWidgets.QApplication(sys.argv)

    # 可选：根据 DPI 缩放字体
    screen = app.primaryScreen()
    dpi = screen.logicalDotsPerInch()
    scale = dpi / 96.0
    font = QFont("Microsoft YaHei", int(10 * scale))
    app.setFont(font)

    dlg = InformationLists()
    dlg.show()
    sys.exit(app.exec())

def run():
    app = QtWidgets.QApplication.instance()
    if app is not None:
        screen = app.primaryScreen()
        dpi = screen.logicalDotsPerInch()
        scale = dpi / 96.0
        font = QFont("Microsoft YaHei", int(10 * scale))
        app.setFont(font)

    dlg = InformationLists()
    dlg.setAttribute(Qt.WidgetAttribute.WA_DeleteOnClose)
    dlg.show()
    return dlg

if __name__ == '__main__':
    main()